package net.toocruel.iqismart.service.core.impl;

import net.toocruel.iqismart.dao.UserRepository;
import net.toocruel.iqismart.dao.core.NotificationRepository;
import net.toocruel.iqismart.entity.core.Notification;
import net.toocruel.iqismart.service.core.NotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description
 * @Auther sty
 * @createTime 2018/5/21 下午5:34
 */
@Service
public class NotificationServiceImpl implements NotificationService {
    @Autowired
    private NotificationRepository notificationRepository;

    @Autowired
    private UserRepository userRepository;
    @Override
    public void send(Notification notification) {
        notificationRepository.save(notification);
    }

    @Override
    public void read(Long id) {
        Notification notification = notificationRepository.findOne(id);
        notification.setRead(true);
        notificationRepository.save(notification);
    }

    @Override
    public void read(Long[] ids) {
        List<Notification> notifications = notificationRepository.findAll((root, query, cb) ->{
            return cb.in(root.get("id").in(ids));
        });
        notifications.forEach(message -> message.setRead(true));
        notificationRepository.save(notifications);
    }

    @Override
    public List<Notification> findByToUser(Long id) {
        return notificationRepository.findAll((root, query, cb) -> {
            return cb.and(cb.equal(root.get("toUser"), id),cb.isFalse(root.get("read")));

        } );
    }
}
